package com.mall.business.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.business.domain.*;
import com.mall.business.service.*;
import com.mall.common.exception.ServiceException;
import com.mall.common.utils.DateUtils;
import com.mall.common.utils.SecurityUtils;
import com.mall.common.utils.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mall.business.mapper.TOrderMapper;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-30
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements ITOrderService {
    @Autowired
    private TOrderMapper tOrderMapper;

    @Autowired
    private ITProductService productService;

    @Autowired
    private ITOrderItemService orderItemService;

    @Autowired
    private ITSeckillService seckillService;


    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public TOrder selectTOrderById(String id) {
        return tOrderMapper.selectTOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param tOrder 订单
     * @return 订单
     */
    @Override
    public List<TOrder> selectTOrderList(TOrder tOrder) {
        List<TOrder> tOrders = tOrderMapper.selectTOrderList(tOrder);
        return tOrders;

    }

    @Override
    public List<TOrder> selectTOrderListApp(TOrder tOrder) {
        List<TOrder> tOrders = tOrderMapper.selectTOrderList(tOrder);
        for (int i = 0; i < tOrders.size(); i++) {
            TOrder tOrder1 = tOrders.get(i);
            String orderNo = tOrder1.getOrderNo();
            List<TOrderItem> orderItemsByOrderNumber = orderItemService.getOrderItemsByOrderNumber(orderNo);
            tOrders.get(i).setOrderItemList(orderItemsByOrderNumber);
        }
        return tOrders;
    }


    /**
     * 新增订单
     *
     * @param tOrder 订单
     * @return 结果
     */
    @Override
    public int insertTOrder(TOrder tOrder) {
        tOrder.setCreateTime(DateUtils.getNowDate());
        return tOrderMapper.insertTOrder(tOrder);
    }

    /**
     * 修改订单
     *
     * @param tOrder 订单
     * @return 结果
     */
    @Override
    public int updateTOrder(TOrder tOrder) {
        tOrder.setUpdateTime(DateUtils.getNowDate());
        return tOrderMapper.updateTOrder(tOrder);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteTOrderByIds(String[] ids) {
        return tOrderMapper.deleteTOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteTOrderById(String id) {
        return tOrderMapper.deleteTOrderById(id);
    }


    @Autowired
    private ITCouponUserService tCouponUserService;


    @Override
    public String createOrder(OrderMergeDTO mergerOrder, String remark, Map<String, TProduct> skuStocksMap) {
        TUserAddress userAddress = mergerOrder.getUserAddress();
        ArrayList<TOrderItem> tzOrderitems = new ArrayList<>();
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        String orderNumber = String.valueOf(snowflake.nextId());
        Boolean scorepay = false;
        mergerOrder.getCartOrders().forEach(cart -> {
            TProduct product = productService.getById(cart.getProductId());
            TOrderItem orderItem = new TOrderItem();
            orderItem.setProductId(cart.getProductId());
            orderItem.setProductName(cart.getProductName());
            orderItem.setImage(product.getImage());
            orderItem.setPrice(cart.getProductPrice());
            orderItem.setPayNum(cart.getCartNum());
            orderItem.setInfo(product.getInfo());
            orderItem.setTotalPrice(NumberUtil.mul(cart.getCartNum(), cart.getProductPrice()));
            orderItem.setIsComment("0");
            orderItem.setProductType(cart.getType());
            orderItem.setUserId(SecurityUtils.getUserIdStr());
            // 秒杀活动Id
            orderItem.setSeckillId(cart.getSeckillId());
            orderItem.setPinkId(cart.getPinkId());
            orderItem.setPtActiveId(cart.getPtId());
            // 未退货
            orderItem.setRefundStatus("0");
            // 积分商品和普通商品
            if (product.getStock() == null) {
                throw new ServiceException("商品：[" + product.getTitle() + "]库存不足");
            }
            // 检验库存
            if (product.getStock() != null && product.getStock() < cart.getCartNum()) {
                throw new ServiceException("商品：[" + product.getTitle() + "]库存不足");
            }
            // 校验限购
            if ("1".equals(product.getIsXg())) {
                Integer xgDay = product.getXgDay();
                Integer xgNum = product.getXgNum();
                if (xgDay == null || xgNum == null) {
                    throw new ServiceException("商品：" + product.getTitle() + "限购配置不完整");
                }
                // 计算限制的开始时间
                Date limitStartDate = DateUtils.addDays(DateUtils.getNowDate(), -xgDay);
                // 查询该用户在限购周期内已购买的数量
                QueryWrapper<TOrder> wrapperorder = new QueryWrapper<>();
                wrapperorder.eq("user_id", SecurityUtils.getUserIdStr());
                wrapperorder.eq("order_status", "2");
                wrapperorder.ge("create_time", limitStartDate); // 限制周期内的订单
                List<TOrder> listorderdate = this.list(wrapperorder);
                Long  yjbugyNum=Long.valueOf(0);
                for (int i = 0; i < listorderdate.size(); i++) {
                    TOrder tOrder = listorderdate.get(i);
                    List<TOrderItem> orderItemsByOrderNumber = orderItemService.getOrderItemsByOrderNumber(tOrder.getOrderNo());
                    for (int j = 0; j < orderItemsByOrderNumber.size(); j++) {
                        TOrderItem orderItemorder = orderItemsByOrderNumber.get(j);
                        if (orderItemorder.getProductId().equals(orderItem.getProductId())) {
                            yjbugyNum=yjbugyNum+orderItemorder.getPayNum();
                        }
                    }
                 }
                if (yjbugyNum + cart.getCartNum() > xgNum) {
                    throw new ServiceException("商品：" + product.getTitle() + "超过限购数量");
                }
            }
            TProduct mapSku = new TProduct();
            mapSku.setId(product.getId());
            // 这里的库存是改变的库存
            mapSku.setStock(cart.getCartNum());
            mapSku.setTitle(product.getTitle());
            skuStocksMap.put(product.getId(), mapSku);
            tzOrderitems.add(orderItem);
        });
        List<TCart> scorecollect = mergerOrder.getCartOrders().stream().filter(e -> e.getType().equals("3")).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(scorecollect)) {
            scorepay = true;
        }
        TOrder order = new TOrder();
        order.setOrderNo(orderNumber);
        order.setUserId(SecurityUtils.getUserIdStr());
        order.setTotalPrice(mergerOrder.getTotalPrice());
        order.setTotalNum(mergerOrder.getTotalNum());
        // 未支付
        order.setOrderStatus("1");
        order.setIsPayed("0");
        order.setIsRefund("0");
        order.setRefundStatus("0");
        order.setRemark(remark);
        if (!StringUtils.isEmpty(mergerOrder.getCouponId())) {
            // 优惠券Id
            order.setCouponId(mergerOrder.getCouponId());
            order.setCouponPrice(mergerOrder.getCouponPrice());
            // 计算优惠券实付金额
            if (mergerOrder.getCouponPrice().compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal paymoney = mergerOrder.getTotalPrice().subtract(mergerOrder.getCouponPrice());
                if (paymoney.compareTo(BigDecimal.ZERO) < 0) {
                    order.setPayPrice(BigDecimal.ZERO);
                } else {
                    order.setPayPrice(paymoney);
                }
            } else {
                order.setPayPrice(mergerOrder.getTotalPrice());
            }
        }
        String couponId = mergerOrder.getCouponId();
        if (StringUtils.isNotEmpty(couponId)) {
            TCouponUser couponUser = new TCouponUser();
            couponUser.setCouponId(couponId);
            couponUser.setUserId(SecurityUtils.getUserIdStr());
            List<TCouponUser> tCouponUsers = tCouponUserService.selectTCouponUserList(couponUser);
            for (TCouponUser tCouponUser : tCouponUsers) {
                // 使用时间
                tCouponUser.setUseTime(DateUtil.date());
                tCouponUser.setStatus("1");
                tCouponUser.setRemark(order.getOrderNo());
                tCouponUserService.updateById(tCouponUser);
            }
        }
        if (scorepay) {
            order.setPayType("2");
            // 使用积分
            order.setUseIntegral(mergerOrder.getTotalPrice());
            order.setPayPrice(BigDecimal.ZERO);
        } else {
            order.setPayPrice(mergerOrder.getTotalPrice());
        }
        order.setCreateTime(DateUtils.getNowDate());
        order.setRealName(userAddress.getName());
        order.setUserPhone(userAddress.getPhone());
        order.setUserAddress(userAddress.getAddress());
        order.setProvince(userAddress.getProvince());
        order.setCity(userAddress.getCity());
        order.setCounty(userAddress.getCounty());
        order.setOrderTime(DateUtils.getNowDate());
        this.save(order);
        tzOrderitems.forEach(item -> {
            item.setOrderNo(orderNumber);
        });
        orderItemService.saveBatch(tzOrderitems);
        return orderNumber;
    }


    @Override
    public TProduct userSkill(String seckillId) {
        TSeckill sekill = seckillService.getById(seckillId);
        Long sales = sekill.getSales();
        // 秒杀校验
        TProduct tProduct = skillValidate(sekill);
        sekill.setTotalNum(sekill.getTotalNum() - 1);
        sales = sales == null ? 0 : sales + 1;
        sekill.setSales(sales);
        seckillService.updateById(sekill);
        return tProduct;

    }

    public TProduct skillValidate(TSeckill sekill) {
        String productId = sekill.getProductId();
        TProduct product = productService.getById(productId);
        if (product == null) {
            throw new ServiceException("秒杀商品不存在");
        }
        if (sekill.getStartTime().compareTo(DateUtils.getNowDate()) > 0) {
            throw new ServiceException("秒杀活动未开始");
        }
        if (sekill.getEndTime().compareTo(DateUtils.getNowDate()) < 0) {
            throw new ServiceException("秒杀活动已结束");
        }

        if (sekill == null) {
            throw new ServiceException("秒杀活动已结束");
        }
        if (sekill.getStatus().equals("0")) {
            throw new ServiceException("秒杀活动已结束");
        }
        if (sekill.getTotalNum() <= 0) {
            throw new ServiceException("秒杀商品已经售罄");
        }
        return product;
    }

    @Autowired
    private ITCouponService tCouponServie;

    @Autowired
    private ITCouponUserService couponUserService;


    @Override
    public void couponValidate(TCoupon coupon) {
        QueryWrapper<TCouponUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", SecurityUtils.getUserIdStr());
        queryWrapper.eq("coupon_id", coupon.getId());
        queryWrapper.eq("status", "0");
        queryWrapper.apply("NOW() BETWEEN start_date AND end_date"); // 使用 SQL 直接过滤有效期内的优惠券
        long count = couponUserService.count(queryWrapper);
        if (count == 0) {
            throw new ServiceException("优惠券不在有效期");
        }

    }


    @Override
    public TOrder getOrderByOrderNo(String orderNo) {
        LambdaQueryWrapper<TOrder> orderquery = new LambdaQueryWrapper<TOrder>().eq(TOrder::getOrderNo, orderNo);
        TOrder order = this.getOne(orderquery);
        return order;

    }

    @Override
    public BigDecimal getOrderPayMoney(String userId) {
        QueryWrapper<TOrder> orderquery = new QueryWrapper<TOrder>();
        orderquery.select("COALESCE(sum(pay_price), 0) as pay_price");
        orderquery.eq("user_id", userId);
        orderquery.in("pay_type", Arrays.asList("1", "3"));
        orderquery.eq("is_payed", "1");
        TOrder order = this.getOne(orderquery);
        return order.getPayPrice();
    }


}
